﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using FluentNHibernate.Cfg;
using NHibernate;

namespace Mindfor.Web.Data
{
	/// <summary>
	/// Provides extensions functions to NHibernate.
	/// </summary>
	public static class NHibernateExtensions
	{
		/// <summary>
		/// Adds fluent mappings from all Mindfor assemblies.
		/// </summary>
		/// <param name="container">Container where to add mappings.</param>
		public static FluentMappingsContainer AddFromMindforAssemblies(this FluentMappingsContainer container)
		{
			foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
			{
				if (asm.FullName.StartsWith("Mindfor"))
					container.AddFromAssembly(asm);
			}
			return container;
		}

		/// <summary>
		/// Copy the state of the given object onto the persistent object with the same
		/// identifier. If there is no persistent instance currently associated with
		/// the session, it will be loaded. Return the persistent instance. If the given
		/// instance is unsaved, save a copy of and return it as a newly persistent instance.
		/// The given instance does not become associated with the session.  This operation
		/// cascades to associated instances if the association is mapped with cascade="merge".
		/// The semantics of this method are defined by JSR-220.
		/// </summary>
		/// <typeparam name="T">Entity type.</typeparam>
		/// <param name="entity">A detached instance with state to be copied.</param>
		/// <returns>An updated persistent instance.</returns>
		public static T MergeEntity<T>(this ISession dataSession, T entity)
		{
			return (T)dataSession.Merge(entity);
		}

		/// <summary>
		/// Persist the given transient instances, first assigning a generated identifier.
		/// </summary>
		/// <param name="objs">A transient instances of a persistent class.</param>
		public static void SaveMulti(this ISession dataSession, IEnumerable objs)
		{
			foreach (object obj in objs)
				dataSession.Save(obj);
		}
	}
}
